package com.yi.wood.web.session;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author MoYi
 * Created time 2019/5/29 16:23
 */
@Component("sessionVerCode")
public class LocalCacheSessionVerCode implements SessionVerCode{

    private volatile Map<String, VerCode> sessionVerCodeMap = new HashMap<>();

    @Override
    public String getCacheVerCode(String sessionId) {
        return sessionVerCodeMap.getOrDefault(sessionId,null).getVal();
    }

    @Override
    public void cacheVerCode(String sessionId, String verCode) {
        sessionVerCodeMap.put(sessionId, new VerCode(verCode, System.currentTimeMillis()+DEFAULT_EXPIRE_TIME));
    }

    @Override
    public boolean isExpire(String sessionId) {
        VerCode verCode = sessionVerCodeMap.getOrDefault(sessionId,null);
        if (Objects.isNull(verCode)){
            return false;
        }
        return verCode.getExpireTime() > System.currentTimeMillis();
    }
}
